# -*- coding: utf-8 -*-

'''

@author: wyndem
@Emil:   wyndem.wen@timevary.com
@FileName: tool.py
@Time: 2018/7/19 14:20
@Description: 工具类

'''
import asyncio
import hashlib
import os
import random
import re
import smtplib
import threading
from email.header import Header
from email.mime.text import MIMEText
from functools import reduce
from queue import Queue

import requests

import config

#浏览器UA
uas = [
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0; Baiduspider-ads) Gecko/17.0 Firefox/17.0",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9b4) Gecko/2008030317 Firefox/3.0b4",
    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; Touch; LCJB; rv:11.0) like Gecko"
]

q = Queue()

def retry(fun):
    def force(*args, **kwargs):
        degree = 0
        while  degree<=10:
            try:
                f=fun(*args, **kwargs)
                return f
            except Exception as e :
                degree+=1
                print(e)
                print('%s正在重试%d/10次'%(fun.__name__,degree))
    return force

@retry
def init_ips():
    if config.is_PRo:
        ips = requests.get(config.PROIP).json()
        if ips.get('code') == 5:
            ip=ips.get("msg").split('登录IP')[0]
            requests.get('http://http.zhiliandaili.com/Users-whiteIpAddNew.html?appid=1606&appkey=e48efc6dd23b9c5a0ee524ceac7331aa&whiteip='+ip+'&index=1')
        if ips.get('code')==0:
            ips=ips.get("data")
            for ip in ips:
                q.put(ip.get('IP'))




class Tool():

    def __init__(self):
        pass

    '获取代理IP'
    def getProXY(self):
        if  not q.empty():
            return  q.get()
        elif config.is_PRo:
            init_ips()
            return self.getProXY()
        else:
            return ''

    '获取伪装浏览器头'
    def getHeaders(self):
        headers=config.HEADERS
        if headers==None or headers=='' or len(headers)==0:
            headers={"Accept-Encoding":"gzip, deflate, br",
                     "Accept-Language":"zh-CN,zh;q=0.8",
                     "Cache-Control":"max-age=0",
                     "Connection":"keep-alive"}
        if headers.get('User-Agent')==None:
            headers['User-Agent'] = uas[random.randint(0, len(uas)-1)]
        return headers


    #获取请求对象
    def getProxies(self):
        ip=self.getProXY()
        return {'http':ip,'https':ip}


    'md5加密'
    def md5Pass(self,pws):
        m = hashlib.md5()
        m.update(pws.encode('utf-8'))
        return m.hexdigest()

    '获取极验的结果'
    def jiyanapi(self, cof):
        r = requests.get(
            'http://jiyanapi.c2567.com/shibie?gt=' + str(cof.get('gt')) + '&challenge=' + str(cof.get('challenge')) + '&referer='+str(cof.get('url') )+ '&user=' + config.j_NAME + '&pass=' + config.j_PWS + '&return=json&model=3')
        return r.json().get('challenge'),r.json().get('validate')

    '获取极验的结果'
    def  jiyanapi_s(self,mst,cof):
        if mst:
            while mst:
                challenge,validate =self.jiyanapi(cof)
                if challenge!=None and validate!=None:
                    return challenge,validate

    '生成密码'
    def create_pwd(self):

        capitalization = [chr(i) for i in range(65, 91)] # 大写字母
        lowercase=[chr(i) for i in range(97, 123)] #小写字母
        number=[chr(i) for i in  range(48,58)] #数字

        cap = random.sample(capitalization, random.randint(1,3))
        low=random.sample(lowercase, random.randint(5,8))
        num=random.sample(number, random.randint(2,3))

        str = ''
        value = str.join(num) + str.join(cap) +str.join(low) # 将取出的十个随机数进行重新合并

        for v in value:
            n=random.randint(1,len(value))
            str+=value[n-1:n]

        return str

    '分割文本'
    def create_mail_text(self):
        f=open(config.path_163,'r')
        #记录当前行
        currently_line=0
        #写出的数据
        data_text=''
        #总行
        sum_line=0





        for line in f.readlines():
            if currently_line==config.thread_num:
                file_name = '%s_' % self.create_pwd() + os.path.basename(config.path_163)
                u = open(os.path.join(self.getPropath(),file_name), 'w+')
                u.write(data_text)
                u.close()
                data_text=''
                currently_line=0

            l = line.strip().replace('\n', '')
            if l == '':
                continue
            sum_line+=1
            currently_line+=1
            data_text=data_text+l+'\n'
        f.close()
        if config.thread_num > sum_line and not data_text=='':
            file_name = '%s_' % self.create_pwd() + os.path.basename(config.path_163)
            u = open(os.path.join(self.getPropath(),file_name), 'w+')
            u.write(data_text)
            u.close()
            return
        if data_text!='':
            file_name = '%s_' % self.create_pwd() + os.path.basename(config.path_163)
            u = open(os.path.join(self.getPropath(),file_name), 'w+')
            u.write(data_text)
            u.close()

    '返回项目根目录'
    def getPropath(self):
        aList = os.getcwd().split('\\')[:-1]
        path = (reduce(lambda x, y: x + '\\' + y, aList))
        return path


    def send_mail(self,mail_title,mail_text):
        host = 'smtp.qq.com'  ##定义smtp主机
        FROM = "wyndem@qq.com"  ##邮件发送人

        msg = MIMEText(mail_text, 'plain', 'utf-8')
        msg['From'] = Header("文燕彤", 'utf-8')   # 发送者
        #msg['To'] = Header("测试", 'utf-8')        # 接收者
        msg['Subject'] = Header(mail_title, 'utf-8').encode()

        server = smtplib.SMTP_SSL(host, "465")  # 创建smtp对象
        #server.connect(host, "25")  ##通过connect方法连接smtp主机
        #server.starttls()  ##启动安全传输模式
        server.login("wyndem@qq.com", 'zdffcxsdbotwcbbf')  ##邮箱账号登录
        server.sendmail(FROM,config.TO, msg.as_string())
        server.quit()

'异步163邮箱登录'
@retry
async def async_login(m,path):
    mail_login=[]
    f = open(path, 'r', encoding='utf-8')
    print('%s'% threading.currentThread())
    for line in f.readlines():
        l = line.strip().replace('\n', '')
        if l == '':
            continue
        l = re.split('-+', l)
        mail_login.append( m.login(l[0], l[1]))
    f.close()

    await asyncio.wait(mail_login)
    return True







TOOL=Tool()

